package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SearchAlbumListemer {

    @Autowired
    private SearchService searchService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = RabbitConstant.ALBUM_UPPER_QUEUE, durable = "true"),
                    exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = "topic", durable = "true"),
                    key = RabbitConstant.ALBUM_UPPER_RK
            )
    )
    public void upperAlbumInfo(Channel channel, Message message, String uniqueAlbumId) throws IOException {

        // redis + token + setnx 进行幂等性校验
        Long albumId = Long.valueOf(uniqueAlbumId.split("-")[1]);
        String redisKey = uniqueAlbumId;
        log.info("接收到消息上架专辑,专辑id:{}", albumId);
       // Boolean res = redisTemplate.opsForValue().setIfAbsent(redisKey, "albumId", RedisConstant.ALBUM_TIMEOUT, TimeUnit.SECONDS);
//        if (!res) {
//            log.warn("上架专辑消息重复消费！！！！！！！！！！"); // 改为warn级别更合适
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
//            return;
//        }
        try {
            searchService.upperAlbumInfoToEs(albumId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 删除key
        } catch (Exception e) {
            if (message.getMessageProperties().isRedelivered()) {
                // 如果是重新投递的消息 则 拒绝
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                log.error("上传专辑,消息消费失败。消息：{}, 专辑id: {}", message, albumId);
            } else {
                // 重新投递 消息
                log.error("count-->上架专辑,消息消费失败。消息：{}, 专辑id: {},正在进行重试......", message, albumId);
                // 第一次消费异常时候 需要删除key
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                //redisTemplate.delete(redisKey);
            }
        }

    }
////    // 下架专辑
//
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = RabbitConstant.ALBUM_DOWN_QUEUE, durable = "true"),
                    exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = "topic", durable = "true"),
                    key = RabbitConstant.ALBUM_DOWN_RK
            )
    )
    public void downAlbumInfo(Channel channel, Message message, String uniqueAlbumId) throws IOException {

        Long albumId = Long.valueOf(uniqueAlbumId.split("-")[1]);
        String redisKey = uniqueAlbumId;
        log.info("接收到消息,下架专辑,id:{}", albumId);
        // redis + token + setnx 进行幂等性校验
       // Boolean res = redisTemplate.opsForValue().setIfAbsent(redisKey, "albumId", RedisConstant.ALBUM_TIMEOUT, TimeUnit.SECONDS);

//        if (!res) {
//            log.warn("下架消息重复消费！！！！！！"); // 改为warn级别更合适
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
//            return;
//        }
        try {
            searchService.downAlbumInfoToEs(albumId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            if (message.getMessageProperties().isRedelivered()) {
                // 如果是重新投递的消息 则拒绝
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                log.error("下架专辑,消息消费失败。消息：{}, 专辑id: {}", message, albumId);
            } else {
                // 重新投递 消息
                log.error("count-->下架专辑,消息消费失败。消息：{}, 专辑id: {},正在进行重试......", message, albumId);
                // 第一次消费异常时候 需要删除key
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
               // redisTemplate.delete(redisKey);
            }
        }

    }



     // 清空消息
//    @RabbitListener(
//            bindings = @QueueBinding(
//                    value = @Queue(value = RabbitConstant.ALBUM_UPPER_QUEUE, durable = "true"),
//                    exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = "topic", durable = "true"),
//                    key = RabbitConstant.ALBUM_UPPER_RK
//            )
//    )
//    public void clear1(Channel channel, Message message, String str){
//        log.info("清除消息,上架专辑,id:{}",str);
//        try {
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
//    }
//
//
//    @RabbitListener(
//            bindings = @QueueBinding(
//                    value = @Queue(value = RabbitConstant.ALBUM_DOWN_QUEUE, durable = "true"),
//                    exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = "topic", durable = "true"),
//                    key = RabbitConstant.ALBUM_DOWN_RK
//            )
//    )
//    public void clear2(Channel channel, Message message, String str){
//        log.info("清除消息,下架专辑,id:{}", str);
//        try {
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }


}
